var querystring = require('querystring');
var url = require('url');
export default function myPlugin(rawOptions) {
    const options = {
        isProduction: process.env.NODE_ENV === 'production',
        ...rawOptions,
        root: process.cwd(),
    };
    let postData; let config;
    return {
        name: 'vite-plugin-pageData', // 必须的，将会显示在 warning 和 error 中 
        configResolved(resolvedConfig) {
            // 存储最终解析的配置
            config = resolvedConfig
        },
        configureServer(server) {
            server.middlewares.use((req, res, next) => {
                let post = '';
                postData = '';
                // console.log(new Date(), 'req.url:', req.url)
                let reqUrl = (req.url || "").split('?')[0];
                let isReqHtml = (req.url === null || req.url === void 0 ? void 0 : reqUrl.endsWith('.html')) && req.headers['sec-fetch-dest'] !== 'script'

                if (isReqHtml == false) {
                    next();
                    return;
                }
                req.on('data', (chunk) => {
                    post += chunk;
                    postData = querystring.parse(post);
                    // console.log(new Date(), 'PostData:', postData);
                });
                next();
            })
        },
        transformIndexHtml(html) {
            // console.log('config.command:',config.command)
            if (config.command === 'build') {
                return html;
            }
            let postDataStr = JSON.stringify(postData || {});
            let varName = options.varName || 'viteRequestData';
            let varGlobal = JSON.stringify(options.global||{});
            let funcName = new Date().valueOf();
            let queryScript = `
            function _viteGetQuery${funcName}() {
                var url = window.location.search;
                var theRequest = new Object();
                if (url.indexOf("?") != -1) {
                  var str = url.substr(1);
                  strs = str.split("&");
                  for(var i = 0; i < strs.length; i ++) {
                    theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]);
                  }
                }
                return theRequest;
              }`
            postData = '';
            let titleStr = html.match(/<head(.*?)>/g)[0]||"";
            return html.replace(
                /<head(.*?)>/g,
                `${titleStr}<script>${queryScript};window.${varName} = Object.assign(_viteGetQuery${funcName}(),${postDataStr});window._global=${varGlobal}; </script>`
            )
        }
    }
}